﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Aliyun.OSS;
using System.Data;
using System.Data.SqlClient;
using System.IO;
namespace DAL
{
    public class OSSHelper
    {
        const string accessKeyId = "LTAIpBtfSVKiFD26";
        const string accessKeySecret = "AqLuVLBCME5iJ1EQkRryQ1ZqyhxLzh";
        const string endpoint = "http://oss-cn-beijing.aliyuncs.com";


        #region 网站oss附件列表
        public string ListObjects(string bucketName, string pre, string del)
        {
            QXHelper QX = new QXHelper();
            var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
            DataTable dt = new DataTable();
            dt.Columns.Add("key", typeof(System.String));
            dt.Columns.Add("size", typeof(System.String));
            try
            {
                var listObjectsRequest = new ListObjectsRequest(bucketName)
                {
                    Prefix = pre,
                    Delimiter = del
                };
                var result = client.ListObjects(listObjectsRequest);
                foreach (var prefix in result.CommonPrefixes)
                {
                    DataRow row = dt.NewRow();
                    row["key"] = prefix;
                    row["size"] = "";
                    dt.Rows.Add(row);
                }
                foreach (var summary in result.ObjectSummaries)
                {
                    DataRow row = dt.NewRow();
                    row["key"] = summary.Key;
                    row["size"] = QX.GetFileSize(summary.Size);
                    dt.Rows.Add(row);
                }


            }
            catch (Exception ex)
            {
                Console.WriteLine("List object failed. {0}", ex.Message);
            }


            return QX.LayuiTableJson(dt);
        }

        #endregion
        #region 网站附件删除
        public bool DeleteObject(string bucketName, string key)
        {

            bool flag = false;
            var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
            try
            {
                client.DeleteObject(bucketName, key);
                flag = true;
            }
            catch (Exception ex)
            {
                flag = false;
            }
            return flag;
        }
        #endregion
        #region 网站图片上传
        public bool PutObject(string bucketName, string key, Stream fileToUpload)
        {
            var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
            bool flag = false;
            try
            {
                var result = client.PutObject(bucketName, key, fileToUpload);
                flag = true;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Put object failed, {0}", ex.Message);
                flag = false;
            }
            return flag;
        }
        #endregion






    }
}
